package com.zyt.controller;

import com.zyt.pojo.Jar;
import com.zyt.service.JarService;
import com.zyt.service.impl.JarServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.*;

@Controller

public class JarController {
    private JarService js=new JarServiceImpl();
    @RequestMapping("/add")
    public String add(MultipartFile myjar, Jar jar) throws IOException {
        String name = myjar.getOriginalFilename();
        String filename= UUID.randomUUID().toString()+name;
        File target = new File("d:/jarFolder/"+filename);
        myjar.transferTo(target);
        jar.setFilename(filename);
        jar.setName(name);
        jar.setSize((int)myjar.getSize());
        js.insert(jar);
        return "redirect:/selectAll.do";
    }
    @RequestMapping("/selectAll")
    public String selectAll(Model model){
        List<Jar> jars =js.selectAll();
        model.addAttribute("jars",jars);
        return "/showAll.jsp";
    }
    @RequestMapping("/download")
    public void download(String name, String filename, HttpServletResponse response) throws Exception {
        //1.通过文件名转换为文件
        File sourceFile=new File("d:/jarFolder/"+filename);
        //2.设置响应格式和文件的名字
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(name,"utf-8"));
        //3.把文件放入到response里面。
       FileUtils.copyFile(sourceFile,response.getOutputStream());
    }
}
